package com.hctforgreen.greenservice;

import java.util.Hashtable;
import java.util.List;

import org.w3c.dom.Text;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.hctforgreen.greenservice.ctr.DbController;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.encoding.RGBLuminanceSource;
import com.hctforgreen.greenservice.model.MachineListEntity.MachineEntity;
import com.hctforgreen.greenservice.ui.adapter.FuzzySearchListAdapter;
import com.hctforgreen.greenservice.utils.CheckDataVersionCodeUtil;
import com.hctforgreen.greenservice.utils.DecodeBitmapUtil;
import com.hctforgreen.greenservice.utils.DownloadBookLstInitFinishUtil;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.ImageCropUtil;
import com.hctforgreen.greenservice.utils.KeyboardUtil;
import com.hctforgreen.greenservice.utils.ThemeStoreUtil;
import com.hctforgreen.greenservice.utils.Utils;
import com.umeng.analytics.MobclickAgent;

/**
 * 调试维修（首页）
 * 
 * @author ld 20140403
 * 
 */
public class DebugActivity extends ParentActivity {
	private EditText search_edit;
	private ImageButton search_btn;
	private Button scan_btn, pic_btn;
	private Activity context;
	public static final int ZXING_DATA = 3024;
	public static final int RESULT_LOAD_IMAGE = 3023;

	private Bitmap bitmap;// 图库二维码图片

	private final int FLAG_MODIFY_FINISH = RESULT_LOAD_IMAGE + 2;

	@Override
	protected void onResume() {
		super.onResume();
		initSkinLayout();
	}


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_debug);
		context = this;
		initWidget();
		initClickEdgehide();
		isUpdateBooksServiceRunning();

	}

	/**
	 * 2016-12-28
	 * 390694 增加判断更新资料的服务是否正在更新，
	 * 更新：提示正在更新资料包，不能查询阅读;
	 * 不更新：若数据库已更新且资料包版本不是最新，则可以查询阅读；
	 * ****  若资料包版本不是最新，则提示去下载管理更新
	 */
	public void isUpdateBooksServiceRunning(){
		boolean isServiceRunning = DownloadBookLstInitFinishUtil.getUpdateBookServiceFinished(context);
		CheckDataVersionCodeUtil checkDataVersionCodeUtil = new CheckDataVersionCodeUtil();
		if (isServiceRunning){
			Dialog dialog = null;
			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			builder.setTitle(R.string.dialog_default_title_hint)
					.setMessage(R.string.update_now)
					.setPositiveButton(R.string.dialog_confirm_hint,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
													int which) {
									dialog.dismiss();
								}
							});
			dialog = builder.create();
			dialog.show();
		}else{
			checkDataVersionCodeUtil.new CheckDataVersionCodeTask(R.string.debug_activity_update_data_content,
					R.string.terminal_update_data_title_2,context, true,
					null, null, null, null, null).execute(context);

		}

	}

	/**
	 * 点击边缘隐藏
	 */
	private void initClickEdgehide() {
		LinearLayout parentLyt = (LinearLayout) findViewById(R.id.lyt_parent);
		parentLyt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setFuzzySearchViewGone();
				KeyboardUtil keyboardUtil = new KeyboardUtil();
				keyboardUtil.hideSoftKeyboard(v);
			}
		});
	}

	private void initWidget() {
		final TextView titleTv = (TextView) findViewById(R.id.tv_title);
		titleTv.setText(getString(R.string.title_debug));
		final ImageButton btn_back = (ImageButton) findViewById(R.id.btn_back);
		btn_back.setOnClickListener(mOnClick);
		scan_btn = (Button) findViewById(R.id.scan_btn);
		scan_btn.setOnClickListener(mOnClick);
		pic_btn = (Button) findViewById(R.id.pic_btn);
		pic_btn.setOnClickListener(mOnClick);

		search_edit = (EditText) findViewById(R.id.search_edit);
		search_btn = (ImageButton) findViewById(R.id.search_btn);
		search_btn.setOnClickListener(mOnClick);
		initFuzzySearchEt(search_edit);
		String barcode = getIntent().getStringExtra("barcode");// 开机密码跳转而来
		if (!TextUtils.isEmpty(barcode) && barcode.length() > 5) {
			search_edit.setText(barcode.subSequence(0, 5));
		}
	}

	private void initFuzzySearchEt(final EditText searchEt) {

		searchEt.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				fuzzySearchMachineList(s.toString().trim());
			}

		});
	}

	private boolean bCanDoFuzzySearch = true;

	private void fuzzySearchMachineList(final String keyWord) {
		final LinearLayout fuzzySearchLyt = (LinearLayout) findViewById(R.id.lyt_fuzzy_search);

		if (!bCanDoFuzzySearch) {
			bCanDoFuzzySearch = true;
			fuzzySearchLyt.setVisibility(View.GONE);
			return;
		}
		if (keyWord.equals("")) {
			fuzzySearchLyt.setVisibility(View.GONE);
			return;
		}
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {

				HctResult hctResult = new HctResult();
				switch (msg.what) {
				case HctConstants.STATUS_SUCCESS:
					fuzzySearchLyt.setVisibility(View.VISIBLE);

					hctResult = (HctResult) msg.obj;

					List<MachineEntity> dataList = (List<MachineEntity>) hctResult.data;

					initFuzzySearchLv(fuzzySearchLyt, dataList);
					break;

				case HctConstants.STATUS_FAILD:

					fuzzySearchLyt.setVisibility(View.GONE);
					break;
				}
			}

			private void initFuzzySearchLv(final LinearLayout fuzzySearchLyt,
					final List<MachineEntity> dataList) {
				ListView fuzzySearchLV = (ListView) fuzzySearchLyt
						.findViewById(R.id.lst_default_list);
				new FuzzySearchListAdapter(DebugActivity.this, fuzzySearchLV,
						dataList);

				fuzzySearchLV.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						bCanDoFuzzySearch = false;
						final MachineEntity entity = (MachineEntity) dataList
								.get(position);
						EditText searchEt = (EditText) findViewById(R.id.search_edit);
						searchEt.setText(entity.name);
						Utils.setLastSelection(searchEt);
						startTechnicalDataMutliLevelActivity();

					}
				});
			}

		};

		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					HctController controller = new HctController(
							DebugActivity.this);

					HctResult result = controller
							.fuzzySearchMachineList(keyWord);
					if (result.status == HctConstants.STATUS_SUCCESS) {
						message.what = result.status;
						message.obj = result;
					} else {
						message.what = HctConstants.STATUS_FAILD;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				handler.sendMessage(message);
			}
		}.start();
	}

	private OnClickListener mOnClick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.btn_back:
				KeyboardUtil keyboardUtil = new KeyboardUtil();
				keyboardUtil.hideSoftKeyboard(v);
				finish();
				break;
			case R.id.search_btn:
				MobclickAgent.onEvent(DebugActivity.this,
						"Search_debug_service");
				startTechnicalDataMutliLevelActivity();
				break;
			case R.id.scan_btn:// 二维码扫描
				Intent intent = new Intent(context, CaptureActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivityForResult(intent, ZXING_DATA);
				break;
			case R.id.pic_btn:// 读取图库二维码
				// startAlbum();
				ImageCropUtil util = new ImageCropUtil();
				util.doCropImage(DebugActivity.this, FLAG_MODIFY_FINISH);
				break;
			default:
				break;
			}
		}

		private void startAlbum() {
			Intent i = new Intent();
			i.setAction(Intent.ACTION_PICK);
			i.setType("image/*");
			startActivityForResult(i, RESULT_LOAD_IMAGE);
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != context.RESULT_OK)
			return;

		if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
				&& null != data) {
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };
			Cursor cursor = getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			cursor.moveToFirst();
			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String picturePath = cursor.getString(columnIndex);
			cursor.close();
			readerFromSDCardPath(picturePath);
		} else if (requestCode == FLAG_MODIFY_FINISH && resultCode == RESULT_OK) {
			if (data != null) {
				ImageCropUtil cropUtil = new ImageCropUtil();
				readerFromSDCardPath(cropUtil.getTmpFilePath());
			}

		} else {
			String result = data.getStringExtra("result");
			search_edit.setText(result);
			Utils.setLastSelection(search_edit);
		}
	}

	private void readerFromSDCardPath(String picturePath) {
		try {
			if (bitmap != null && !bitmap.isRecycled()) {
				bitmap.recycle();
				bitmap = null;
			}
			DecodeBitmapUtil decodeBitmapUtil = new DecodeBitmapUtil();
			bitmap = decodeBitmapUtil.getHorizontalBitmap(picturePath);
			Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
			RGBLuminanceSource source = new RGBLuminanceSource(bitmap);
			BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
			MultiFormatReader reader2 = new MultiFormatReader();
			Result result;
			try {
				result = reader2.decode(bitmap1, hints);
				search_edit.setText(result.getText());
				Utils.setLastSelection(search_edit);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Utils.showToastCenter(context,
						getString(R.string.not_found_the_barcode_hint));
			}
		} catch (Exception e) {
		}
	}

	private void startTechnicalDataMutliLevelActivity() {
		boolean isServiceRunning = DownloadBookLstInitFinishUtil.getUpdateBookServiceFinished(context);
		if (isServiceRunning){
			Dialog dialog = null;
			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			builder.setTitle(R.string.dialog_default_title_hint)
					.setMessage(R.string.update_now)
					.setPositiveButton(R.string.dialog_confirm_hint,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
													int which) {
									dialog.dismiss();
								}
							});
			dialog = builder.create();
			dialog.show();
			return;
		}
		String sUserInput = search_edit.getText().toString().trim();
		if (sUserInput.equals("")) {
			Toast.makeText(DebugActivity.this,
					R.string.edit_input_can_not_null, Toast.LENGTH_SHORT)
					.show();
			return;
		}
		DbController dbController = new DbController(DebugActivity.this);
		MachineEntity machineEntity = dbController.getMachineEntity(sUserInput);
		if (machineEntity == null) {
			Toast.makeText(DebugActivity.this,
					R.string.edit_input_select_is_null, Toast.LENGTH_SHORT)
					.show();
			return;
		}
		Intent intent = new Intent();
		intent.setClass(DebugActivity.this, DebugBooksActivity.class);
		intent.putExtra(HctConstants.ON_ACTIVITY_KEY_MACHINE_ENTITY,
				machineEntity);
		startActivity(intent);
	}

	private boolean setFuzzySearchViewGone() {
		final View fuzzySearchView = findViewById(R.id.lyt_fuzzy_search);
		if (fuzzySearchView.getVisibility() == View.VISIBLE) {
			fuzzySearchView.setVisibility(View.GONE);
			return true;
		}
		return false;
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if (setFuzzySearchViewGone()) {
				return true;
			}
			return super.onKeyDown(keyCode, event);
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}
}
